#include <assert.h>

#include "dialog.h"

EXPORT widget_t *create_dialog(text,x,y,width,height)
    char *text;
    int32_t x,y;
    uint32_t width,height;
{
    // calculate center coordinates if x or y is negative
    if(x<0) {
        uint32_t syswidth = GetSystemMetrics(SM_CXSCREEN);
        x = syswidth/2 - width/2;
    }
    if(y<0) {
        uint32_t sysheight = GetSystemMetrics(SM_CYSCREEN);
        y = sysheight/2 - height/2;
    }
    // allocate memory for the widget
    widget_t *self = malloc(sizeof(widget_t));
    assert(self != NULL);
    // copy the text string
    self->text = malloc(strlen(text)+1);
    assert(self->text != NULL);
    strcpy(self->text, text);
    // create the window
    self->hwnd = CreateWindowEx(0, "WIDGET", self->text, WS_VISIBLE|WS_BORDER|
        WS_CAPTION|WS_DLGFRAME|WS_POPUP|WS_SYSMENU, x, y, width, height,
        NULL, NULL, GetModuleHandle(0), NULL);
    assert(self->hwnd != NULL);
    // bind the widget handler with the callback function
    self->callback = callback_bind(self->hwnd, self);
    self->callback->paint = dialog_paint;
    // set value for the widget
    self->parent = NULL;
    self->width = width;
    self->height = height;
    self->ext = NULL;
    self->memhdc = NULL;
    self->bmp = NULL;
    self->oldbmp = NULL;
    self->backbuf = NULL;
    // return a pointer to the widget
    return self;
}

EXPORT void dialog_set_text(widget_t *self, char *text)
{
    // free the old text, alloc a new string and copy the given text
    free(self->text);
    self->text = malloc(strlen(text)+1);
    assert(self->text != NULL);
    strcpy(self->text, text);
    // send the text to dialog
    SendMessage(self->hwnd, WM_SETTEXT, 0, (WPARAM)self->text);
}

void dialog_paint(widget_t *self, HDC hdc)
{
    RECT rect;
    GetClientRect(self->hwnd, &rect);
    // fill the background with default color
    FillRect(hdc, &rect, (HBRUSH)(COLOR_3DFACE+1));
}

